/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "key.h"
#include "pd.h"
#include "pd_driver.h"
#include "ufcs.h"
#include "qc.h"
#include "afc.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t g_device_address = 0x00;
uint32_t ADDR_Flash_Addr = 0x801F000;

void Set_Device_Addr(uint8_t addr)
{
    uint64_t* falsh_addr = (uint64_t*)ADDR_Flash_Addr;
    uint64_t addr_data = 0x5500 | addr;
    HAL_FLASH_Unlock();
    for(int i = 0; i < 4096 / 8; i ++)
    {
        if((*falsh_addr & 0xFFFF) == 0xFFFF)
        {
            HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, (uint32_t)falsh_addr, addr_data);
            HAL_FLASH_Lock();
            g_device_address = addr;
            return;
        }
        
        if((*falsh_addr & 0xFFFF) != 0)
        {
            HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, (uint32_t)falsh_addr, 0);
        }
        falsh_addr ++;
    }
    //HAL_FLASHEx_Erase(); // To Do
    HAL_FLASH_Lock();
}

uint8_t Get_Device_Addr(void)
{
    uint64_t* falsh_addr = (uint64_t*)ADDR_Flash_Addr;
    for(int i = 0; i < 4096 / 8; i ++)
    {
        if((*falsh_addr & 0xFF00) == 0x5500)
        {
            return *falsh_addr & 0x3F;
        }
        if((*falsh_addr & 0xFFFF) == 0xFFFF)
        {
            break;
        }
        falsh_addr ++;
    }
    return 0;
}

void System_CMD_Proc(PowerV_CMD *powerv_cmd)
{
	switch(powerv_cmd -> cmd)
	{
		case 0x00:  // get Version
            powerv_cmd -> result = 0;
            powerv_cmd -> para_len = 3;
            powerv_cmd -> para[0] = 0; // Master Version
            powerv_cmd -> para[1] = 1;
            powerv_cmd -> para[2] = g_device_address;
			CMD_Response(powerv_cmd);
			break;
		case 0x01:
			wave_upload = powerv_cmd -> para[0];
			powerv_cmd -> result = 0;
            powerv_cmd -> para_len = 0;
			CMD_Response(powerv_cmd);
			break;
		case 0x02:
            powerv_cmd -> result = 0;
            powerv_cmd -> para_len = 12;
			Copy_ADC_Value(powerv_cmd -> para);
			CMD_Response(powerv_cmd);
        case 0x03:
            Set_Device_Addr(powerv_cmd -> para[0]);
            powerv_cmd -> result = 0;
            powerv_cmd -> para_len = 0;
            CMD_Response(powerv_cmd);
	}
}

void CMD_Process(PowerV_CMD *powerv_cmd)
{
	switch(powerv_cmd -> protocol)
	{
		case 0x00:
			System_CMD_Proc(powerv_cmd);
			break;
		case 0x01:
			PD_CMD_Proc(powerv_cmd);
			break;
		case 0x02:
			UFCS_CMD_Proc(powerv_cmd);
			break;
		case 0x03:
			QC_CMD_Proc(powerv_cmd);
			break;
		case 0x04:
			AFC_CMD_Proc(powerv_cmd);
			break;
		default:
			break;
	}
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	switch(GPIO_Pin)
	{
		case GPIO_PIN_4: // Pd Phy Interrupt
			FUSB_IRQHandler();
			break;
		
		case Key_PD_PIN: // PD Key
			PD_Key_IRQHandler();
			break;
		
		case Key_UFCS_PIN: // UFCS Key
			UFCS_Key_IRQHandler();
			break;
		
		case Key_QC_PIN: // QC Key
			QC_Key_IRQHandler();
			break;
		
		case Key_AFC_PIN: // User_AFC Key
			AFC_Key_IRQHandler();
			break;
		
		case Key_UserA_PIN: // User_A Key
			UserA_Key_IRQHandler();
			break;
		
		case Key_SHIFT_PIN: // User_B Key
			SHIFT_Key_IRQHandler();
			break;
	}
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC2_Init();
  MX_USART1_UART_Init();
  MX_I2C3_Init();
  MX_USART3_UART_Init();
  MX_DAC1_Init();
  MX_TIM7_Init();
  MX_TIM6_Init();
  /* USER CODE BEGIN 2 */
    HAL_ADCEx_Calibration_Start(&hadc2, 0);
    g_device_address = Get_Device_Addr();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
    My_Uart1_Rx_Start();
    
    log_printf("Hello PowerV G4\r\n");
    
  while (1)
  {
    UART_CMD_Loop();
    Key_Loop();
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
  RCC_OscInitStruct.PLL.PLLN = 85;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
